package com.tsfyun.scm.filter;

import cn.hutool.core.collection.CollUtil;
import com.tsfyun.common.base.support.HttpServletRequestWrapper;
import com.tsfyun.common.base.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

@Slf4j
@WebFilter(filterName="customRequestFilter",urlPatterns="/*")
public class CustomRequestFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(servletRequest instanceof HttpServletRequest) {
            //对HttpServletRequest进行重新包装，支持json流可以重复读取
            HttpServletRequestWrapper servletRequestWrapper = new HttpServletRequestWrapper((HttpServletRequest) servletRequest);
            //websocket增加请求头参数，网关层增加无效
            String upgradeHeader = servletRequestWrapper.getHeader("Upgrade");
            if (StringUtils.isNotEmpty(upgradeHeader) && "websocket".equalsIgnoreCase(upgradeHeader)) {
                servletRequestWrapper.addHeader("Connection","upgrade");
            }
            filterChain.doFilter(servletRequestWrapper, servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

}
